package com.coocaa.launcher.pattern.normal.pick;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnHoverListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.coocaa.app.gamecenter.pages.home.GameMainActivity;
import com.coocaa.launcher.EasyLauncherActivity;
import com.coocaa.launcher.LauncherBaseActivity;
import com.coocaa.launcher.framework.launcherhost.view.AppItemView;
import com.coocaa.launcher.framework.manager.configdata.data.LauncherAppItemTableData.APP_ITEM_TYPE;
import com.coocaa.launcher.framework.manager.configdata.data.LauncherAppItemTableData.AppEntryData;
import com.coocaa.launcher.framework.manager.configdata.data.LauncherAppItemTableData.AppItemData;
import com.coocaa.launcher.framework.manager.configdata.data.LauncherAppItemTableData.AppShortCutData;
import com.coocaa.launcher.pattern.normal.NormalController;
import com.coocaa.launcher.pattern.normal.UIConfig;
import com.coocaa.launcher.pattern.normal.hotseat.FocusView;
import com.coocaa.launcher.pattern.normal.item.AppBaseItemView;
import com.coocaa.launcher.pattern.normal.item.AppEntry;
import com.coocaa.launcher.pattern.normal.item.AppShortcut;
import com.coocaa.launcher.pattern.normal.util.ItemViewFactory;
import com.coocaa.launcher.util.Utils;
import com.coocaa.x.framework.utils.LiteURI;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litecontent.LiteContentServiceConnecter;
import com.coocaa.x.service.litecontent.data.apps.com_coocaa_app.AppData;
import com.coocaa.x.service.litecontent.data.apps.com_coocaa_app.RP_Installed_Apps;
import com.coocaa.x.service.litepm.aidl.ILitePMInstallListener;
import com.coocaa.x.service.litepm.aidl.ILitePMUninstallListener;
import com.coocaa.x.service.litepm.data.AppInfo;
import com.coocaa.x.service.litepm.data.InstallParams;
import com.coocaa.x.service.litepm.data.MActivityInfo;
import com.coocaa.x.uipackage.BaseView;
import com.coocaa.x.uipackage.SkinManager;
import com.coocaa.x.uipackage.SkinManager.OnThemeChangeListener;
import com.tianci.appstore.AppStoreActivity;
import com.tianci.appstore.R;
import com.tianci.appstore.utils.SkyConstants;

import java.util.ArrayList;
import java.util.List;

public class PickActivity extends LauncherBaseActivity {
    private BaseView contentLayout;
    private List<AppItemData> dataList = new ArrayList<AppItemData>();
    private List<AppItemData> hotSeatList;
    private TextView tipText;
    private GridView gridView;
    private FocusView focusImage;
    private int horizontalSpacing;
    private int verticalSpacing;
    private int firstItemLeft;
    private int hoverIndex = -1;
    private static PickResultListener pickResultListener = null;

    private int selectedResId = R.drawable.hot_seat_focus_bg;
    private int gridViewWidth;
    private AppBaseItemView lastSelectView = null;
    private boolean firstAddStateInited = false;

    public static PickActivity pickActivity = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        pickActivity = this;
        Intent intent = getIntent();
        if (intent == null) {
            Toast.makeText(this, "Intent不可以为空！！！！！", Toast.LENGTH_LONG).show();
            return;
        }
        // listener = (PickResultListener) intent.getSerializableExtra("listener");
        // int filter = intent.getIntExtra(Intent.ACTION_PICK, APP_ITEM_TYPE.APP_ENTRY_TYPE.flag);
        initDataList();// filter);
        registeInstallListener();
        createView();
    }

    private void initDataList()// int filter)
    {
        dataList.clear();
        if (NormalController.hostContext != null)
            hotSeatList = NormalController.hostContext.getAllItems(false);

        int filter = APP_ITEM_TYPE.APP_ENTRY_TYPE.flag;
        int entryFlag = APP_ITEM_TYPE.APP_ENTRY_TYPE.flag;
        if ((filter & entryFlag) == entryFlag) // 需要获取应用程序类型
        {
            // List<AppInfo> appList = AppManager.getInstance().getLocalApps().getInstalledApps();
            LiteURI uri = LiteURI.create("apps://com.coocaa.app/installed_apps");
            uri.addParams("filter", "launcherpick");
            String json = null;
            try {
                json = LiteContentServiceConnecter.getService().call(uri.toString());
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            List<AppInfo> appList = new ArrayList<AppInfo>();
            if (json != null) {
                RP_Installed_Apps rp = RP_Installed_Apps
                        .parseJObject(json, RP_Installed_Apps.class);
                List<AppData> appdatas = rp.resource.resource_items;
                for (AppData appdata : appdatas)
                    appList.add(appdata.info);
            }
            // List<AppInfo> _appList = new ArrayList<AppInfo>();
            // for (AppInfo appInfo : appList)
            // try
            // {
            // _appList.add(appInfo.clone());
            // } catch (CloneNotSupportedException e1)
            // {
            // e1.printStackTrace();
            // }
            // if (_appList != null && _appList.size() > 0)
            // {
            // for (AppInfo info : _appList)
            // {
            // boolean added = false;
            // if (hotSeatList != null && hotSeatList.size() > 0)
            // {
            // for (AppItemData hotData : hotSeatList)
            // {
            // try
            // {
            // if (info.activityList != null && info.activityList.size() > 0)
            // {
            // for (MActivityInfo aInfo : info.activityList)
            // {
            // for (AppItemData d : dataList)
            // {
            // if (d.getMainActivity().equals(aInfo.className))
            // {
            // dataList.remove(d);
            // break;
            // }
            // }
            // }
            // for (MActivityInfo aInfo : info.activityList)
            // {
            // if (aInfo.className.equals(hotData.getMainActivity()))
            // {
            // info.activityList.remove(aInfo);
            // break;
            // }
            // }
            // } else
            // {
            // if (info.pkgName.equals(hotData.getPackageName()))
            // {
            // added = true;
            // break;
            // }
            // }
            // } catch (Exception e)
            // {
            //
            // }
            // }
            // }
            boolean isAppStoreAdd = false;
            boolean isGameAdd = false;
            if (appList != null && appList.size() > 0) {
                for (AppInfo info : appList) {
                    boolean added = false;

                    if (hotSeatList != null && hotSeatList.size() > 0) {
                        for (AppItemData hotData : hotSeatList) {
                            if (hotData.getMainActivity().equals(GameMainActivity.class.getName()))
                                isGameAdd = true;
                            if (hotData.getMainActivity().equals(AppStoreActivity.class.getName()))
                                isAppStoreAdd = true;
                            if (info.pkgName.equals(hotData.getPackageName())
                                    && !info.pkgName.equals("com.tianci.appstore")) {
                                LogUtils.d("app", "app is added pkg:" + info.pkgName);
                                added = true;
                                break;
                            }
                        }
                    }
                    LogUtils.d("app", " pkg:" + info.pkgName + " added:" + added + " isGameAdd:"
                            + isGameAdd + " isAppStoreAdd:" + isAppStoreAdd);
                    if (!added) {
                        if (info.activityList.size() > 1) {
                            for (MActivityInfo aInfo : info.activityList) {
                                if (aInfo.className.equals(EasyLauncherActivity.class.getName())) {
                                } else if (aInfo.className.equals(GameMainActivity.class.getName())
                                        && !isGameAdd) {
                                    AppEntryData data = new AppEntryData();
                                    data.setTitle(aInfo.name);
                                    data.setPackageName(info.pkgName);
                                    data.setActivityName(aInfo.className);
                                    // if (aInfo.className.equals(GameMainActivity.class.getName()))
                                    // dataList.add(0, data);
                                    // else if (aInfo.className.equals(AppStoreActivity.class
                                    // .getName()))
                                    // {
                                    // if (dataList.size() == 0)
                                    // {
                                    // dataList.add(0, data);
                                    // } else
                                    // {
                                    // dataList.add(1, data);
                                    // }
                                    // } else
                                    LogUtils.d("app", "**isAppStoreAdd:" + isAppStoreAdd);
                                    if (!isAppStoreAdd) {
                                        for (AppItemData itemData : dataList) {
                                            AppEntryData entryData = (AppEntryData) itemData;
                                            LogUtils.d("app",
                                                    "entryData.getActivityName():"
                                                            + entryData.getActivityName());
                                            if (entryData.getActivityName().equals(
                                                    AppStoreActivity.class.getName())) {
                                                int loc = dataList.indexOf(itemData);
                                                LogUtils.d("app", "AppStoreActivity  loc:" + loc);
                                                dataList.add(loc, data);
                                            }
                                        }
                                    } else {
                                        dataList.add(data);
                                    }
                                } else if (aInfo.className.equals(AppStoreActivity.class.getName())
                                        && !isAppStoreAdd) {
                                    AppEntryData data = new AppEntryData();
                                    data.setTitle(aInfo.name);
                                    data.setPackageName(info.pkgName);
                                    data.setActivityName(aInfo.className);
                                    dataList.add(data);
                                }
                            }
                        } else {
                            AppEntryData data = new AppEntryData();
                            data.setTitle(info.appName);
                            data.setPackageName(info.pkgName);
                            data.setActivityName(info.mainActivity);
                            if (!info.pkgName.equals("com.tianci.appstore"))
                                dataList.add(data);
                        }
                    }
                }
            }
        }
    }

    private void createView() {
        initContentView();

        focusImage = new FocusView(this);
        SkinManager.getInstance().setBackgroundResource(focusImage, selectedResId);

        initGridView();
        gridView.scrollTo(0, 0);

        int viewWidth = UIConfig.hotSeatItemWidth + 2 * UIConfig.focusBorderWidth;
        int viewHeight = UIConfig.appItemHeight + 2 * UIConfig.focusBorderWidth;
        FrameLayout.LayoutParams initFocusParams = new FrameLayout.LayoutParams(viewWidth,
                viewHeight);
        initFocusParams.leftMargin = firstItemLeft - UIConfig.focusBorderWidth;
        initFocusParams.topMargin = verticalSpacing - UIConfig.focusBorderWidth;
        contentLayout.addView(focusImage, initFocusParams);

        showEmptyTipIfNecessary();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub
        registeInstallListener();
        // initDataList();
        // if(gridView != null)
        // ((BaseAdapter)gridView.getAdapter()).notifyDataSetChanged();
        refreshData();
        super.onNewIntent(intent);
        new Thread() {
            @Override
            public void run() {
                while (lastSelectView == null) {
                    lastSelectView = ((AppBaseItemView) gridView.getChildAt(gridView
                            .getSelectedItemPosition()));
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                gridView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            lastSelectView.setAddState(true);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }, 200);
            }
        }.start();
    }

    private void initContentView() {
        contentLayout = new BaseView(this);
        contentLayout.setClickable(false);
        contentLayout.setFocusable(false);
        contentLayout.setFocusableInTouchMode(false);
        contentLayout.setOnThemeChangeListener(new OnThemeChangeListener() {
            @Override
            public void onThemeChange() {
                // TODO Auto-generated method stub
                SkinManager.getInstance().setBackgroundResource(contentLayout,
                        R.drawable.launcher_bg);
                SkinManager.getInstance().setBackgroundColor(focusImage, selectedResId);
            }
        });
        SkinManager.getInstance().setBackgroundResource(contentLayout, R.drawable.launcher_bg);
        setContentView(contentLayout);
    }

    private void initGridView() {
        gridView = (GridView) getLayoutInflater().inflate(R.layout.gridview_customize, null);// new
        // GridView(this);
        gridView.setSelector(android.R.color.transparent);
        gridView.setNumColumns(UIConfig.PickAppColumnCount);
        gridView.setSmoothScrollbarEnabled(true);
        gridView.setAdapter(new PickAdapter(this, dataList));
        horizontalSpacing = SkyConstants.Div(71);
        verticalSpacing = SkyConstants.Div(93);
        gridViewWidth = UIConfig.PickAppColumnCount * UIConfig.hotSeatItemWidth
                + (UIConfig.PickAppColumnCount - 1) * horizontalSpacing;
        firstItemLeft = (Utils.getScreenWidth(this) - gridViewWidth) / 2;
        gridView.setVerticalSpacing(verticalSpacing);
        gridView.setColumnWidth(horizontalSpacing + UIConfig.hotSeatItemWidth);
        gridView.setStretchMode(GridView.NO_STRETCH);
        gridView.setPadding(firstItemLeft, verticalSpacing, 0, verticalSpacing);
        // 不知道为什么setOnItemClickListener完全没有响应。。。
        // 找到原因了，adapter中的itemView不可获取焦点，否则会截掉“确定”键，则不会执行itemClick
        gridView.setOnItemClickListener(itemClickListener);
        gridView.setOnItemSelectedListener(gridItemSelectListener);
        gridView.setOnKeyListener(gridKeyListener);
        contentLayout.addView(gridView, new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
    }

    private OnItemClickListener itemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // TODO Auto-generated method stub
            clickItem(position);
        }
    };

    private OnClickListener gridClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (v.getId() >= 0 && v.getId() < dataList.size())
                clickItem(v.getId());
        }
    };

    public static void setPickResultListener(PickResultListener listener) {
        PickActivity.pickResultListener = listener;
    }

    private void clickItem(int pos) {
        // TODO Auto-generated method stub
        if (pickResultListener == null)
            return;
        AppItemData info = dataList.get(pos);
        Intent intent = new Intent();
        intent.putExtra("APP_ITEM_TYPE", info.getType());
        if (info.getType() == APP_ITEM_TYPE.APP_ENTRY_TYPE.toString()) {
            AppEntryData entryData = (AppEntryData) info;
            intent.putExtra("title", entryData.getTitle());
            intent.putExtra("localIconPath", entryData.getLocalPath());
            intent.putExtra("iconUrl", entryData.getIconUrl());
            intent.putExtra("packageName", entryData.getPackageName());
            intent.putExtra("activityName", entryData.getActivityName());
        }
        // setResult(Activity.RESULT_OK, intent);
        pickResultListener.onPickResult(0, Activity.RESULT_OK, intent);
        clearInstallListener();
        moveTaskToBack(true);
    }

    private void showEmptyTipIfNecessary() {
        if (dataList == null || dataList.size() == 0) {
            gridView.setVisibility(View.INVISIBLE);
            focusImage.setVisibility(View.INVISIBLE);
            if (tipText == null) {
                tipText = new TextView(this);
                SkinManager.getInstance().setTextColor(tipText, R.color.tipColor);
                tipText.setTextSize(SkyConstants.Dpi(29));
                tipText.setText(SkinManager.getInstance().getString(R.string.all_apps_added));
                contentLayout.addView(tipText, new FrameLayout.LayoutParams(
                        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER));
            }
            tipText.setVisibility(View.VISIBLE);
        } else {
            if (tipText != null)
                tipText.setVisibility(View.INVISIBLE);
            gridView.setVisibility(View.VISIBLE);
            focusImage.setVisibility(View.VISIBLE);
        }
    }

    private OnItemSelectedListener gridItemSelectListener = new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            // TODO Auto-generated method stub
            if (lastSelectView != null) {
                lastSelectView.setAddState(false);
            }
            if (view instanceof AppBaseItemView) {
                lastSelectView = (AppBaseItemView) view;
                lastSelectView.setAddState(true);
            } else {
                lastSelectView = null;
            }
            int left = view.getLeft() - UIConfig.focusBorderWidth + gridView.getLeft();
            int top = view.getTop() - UIConfig.focusBorderWidth + gridView.getTop();
            int viewWidth = view.getWidth() + 2 * UIConfig.focusBorderWidth;
            int viewHeight = view.getHeight() + 2 * UIConfig.focusBorderWidth;
            if (focusImage.getVisibility() != View.VISIBLE)
                focusImage.setFocusPos(left, top, viewWidth, viewHeight);
            else
                focusImage.changeFocusPos(left, top, viewWidth, viewHeight);
            focusImage.setVisibility(View.VISIBLE);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // TODO Auto-generated method stub
            if (lastSelectView != null) {
                lastSelectView.setAddState(false);
                lastSelectView = null;
            }
            focusImage.setVisibility(View.INVISIBLE);
        }
    };

    private OnKeyListener gridKeyListener = new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            // TODO Auto-generated method stub
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT
                        || keyCode == KeyEvent.KEYCODE_DPAD_UP
                        || keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                    if (hoverIndex != -1) {
                        if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
                            if (hoverIndex > 0)
                                gridView.setSelection(hoverIndex - 1);
                            else
                                gridView.setSelection(hoverIndex);
                        }
                        if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
                            if (hoverIndex < dataList.size() - 1)
                                gridView.setSelection(hoverIndex + 1);
                            else
                                gridView.setSelection(hoverIndex);
                        }
                        if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
                            if (hoverIndex >= gridView.getNumColumns())
                                gridView.setSelection(hoverIndex - gridView.getNumColumns());
                            else
                                gridView.setSelection(hoverIndex);
                        }
                        if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                            if (hoverIndex < dataList.size() - gridView.getNumColumns())
                                gridView.setSelection(hoverIndex + gridView.getNumColumns());
                            else
                                gridView.setSelection(hoverIndex);
                        }
                        hoverIndex = -1;
                        return true;
                    }
                }
            }
            return false;
        }
    };

    private OnHoverListener hoverListener = new OnHoverListener() {
        @Override
        public boolean onHover(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            if (event.getAction() == MotionEvent.ACTION_HOVER_MOVE) {
                int left = v.getLeft() - UIConfig.focusBorderWidth + gridView.getLeft();
                int top = v.getTop() - UIConfig.focusBorderWidth + gridView.getTop();
                int viewWidth = v.getWidth() + 2 * UIConfig.focusBorderWidth;
                int viewHeight = v.getHeight() + 2 * UIConfig.focusBorderWidth;
                focusImage.changeFocusPos(left, top, viewWidth, viewHeight);
                focusImage.setVisibility(View.VISIBLE);
                hoverIndex = v.getId();
            }

            return false;
        }
    };

    class PickAdapter extends BaseAdapter {
        private Context mContext;
        private List<AppItemData> dataList;

        public PickAdapter(Context context, List<AppItemData> dataList) {
            this.mContext = context;
            this.dataList = dataList;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            AppItemData data = dataList.get(position);
            if (convertView == null) {
                AppItemView layout = ItemViewFactory.createItemView(mContext, data);
                layout.setFocusable(false);
                layout.setOnHoverListener(hoverListener);
                layout.setLayoutParams(new AbsListView.LayoutParams(UIConfig.hotSeatItemWidth,
                        UIConfig.appItemHeight));
                convertView = layout;
            } else {
                APP_ITEM_TYPE type = APP_ITEM_TYPE.valueOf(data.getType());
                if (type == APP_ITEM_TYPE.APP_ENTRY_TYPE) {
                    ((AppEntry) convertView).update((AppEntryData) data);
                } else if (type == APP_ITEM_TYPE.APP_SHORTCUT_TYPE) {
                    ((AppShortcut) convertView).update((AppShortCutData) data);
                }
                // else if(type == APP_ITEM_TYPE.APP_ENTRY_TYPE)
                // {
                // ((AppWidget) convertView).update((AppWidgetData) dataList.get(position));
                // }
                // else if(type == APP_ITEM_TYPE.APP_ENTRY_TYPE)
                // {
                // ((AppFolder) convertView).update((AppFolderData) dataList.get(position));
                // }
            }

            convertView.setOnClickListener(gridClickListener);
            convertView.setId(position);
            return convertView;
        }

        @Override
        public int getItemViewType(int position) {
            // TODO Auto-generated method stub
            return APP_ITEM_TYPE.valueOf(dataList.get(position).getType()).flag;
        }

        @Override
        public int getViewTypeCount() {
            // TODO Auto-generated method stub
            return 4;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            if (dataList != null)
                return dataList.size();
            return 0;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        LogUtils.d("key", "onkeydown, keycode == " + keyCode);
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            clearInstallListener();
            moveTaskToBack(true);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        // TODO Auto-generated method stub
        try {
            if (hasFocus && !firstAddStateInited) {
                if (dataList.size() != 0) {
                    gridView.setSelection(0);
                    lastSelectView = ((AppBaseItemView) gridView.getChildAt(gridView
                            .getSelectedItemPosition()));
                    lastSelectView.setAddState(true);
                }
                firstAddStateInited = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onWindowFocusChanged(hasFocus);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        clearInstallListener();
        pickResultListener = null;
        pickActivity = null;
        super.onDestroy();
    }

    private void registeInstallListener() {
        try {
            XServiceManager.getLitePMService().addInstallListener(installStub);
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            XServiceManager.getLitePMService().addUninstallListener(uninstallStub);
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void clearInstallListener() {
        LogUtils.d("pick", "PickActivity--clearInstallListener");
        try {
            XServiceManager.getLitePMService().removeInstallListener(installStub);
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            XServiceManager.getLitePMService().removeUninstallListener(uninstallStub);
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void refreshData() {
        initDataList();
        showEmptyTipIfNecessary();
        if (gridView != null && gridView.getVisibility() == View.VISIBLE)
            ((BaseAdapter) gridView.getAdapter()).notifyDataSetChanged();
    }

    @Override
    public String getName() {
        // TODO Auto-generated method stub
        return "电视派选择应用页面";
    }

    private ILitePMInstallListener.Stub installStub = new ILitePMInstallListener.Stub() {
        @Override
        public void onInstallStart(String arg0, AppInfo appInfo, final InstallParams params) throws RemoteException {
            // TODO Auto-generated method stub

        }

        @Override
        public void onInstallEnd(String apkfile, AppInfo appInfo, int success, String extra, final InstallParams params)
                throws RemoteException {
            if (success == 0) {
                LogUtils.d("pick", "install success");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        refreshData();
                    }
                });
            }
        }
    };

    private ILitePMUninstallListener.Stub uninstallStub = new ILitePMUninstallListener.Stub() {
        @Override
        public void onUninstallStart(AppInfo appInfo) throws RemoteException {
            // TODO Auto-generated method stub

        }

        @Override
        public void onUninstallEnd(AppInfo appInfo, int success, String extra)
                throws RemoteException {
            if (success == 0) {
                LogUtils.d("pick", "uninstallend");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        refreshData();
                    }
                });
            }
        }
    };
}
